import { useState, useEffect } from "react";
import getApi from "../../result/api";
import '../../css/Message.scss'
function Notice() {
   const [ws, setWs] = useState(null);
   const [title, setTitle] = useState("");
   const [content, setContent] = useState("");
   const [isConnected, setIsConnected] = useState(false);

   const getNotices = async () => {
      const { result, code } = await getApi({ url: "/Notice/notices" });
      console.log(result, code);
   };

   let [lastSendTime, setLastSendTime] = useState(0); // 上一次发送的时间戳  
   const throttleDelay = 2000; // 节流间隔，单位为毫秒  
   const sendNotices = () => {
      const currentTime = Date.now();
      if (currentTime - lastSendTime < throttleDelay) {
         alert("请勿频繁发送")
         return;
      }
      // 更新上一次发送的时间  
      setLastSendTime(currentTime);
      if (ws && isConnected) {
         ws.send(JSON.stringify({ type: "Notices", message: { title, content } }));
      } else {
         console.error("WebSocket未连接，无法发送消息");
      }
   };

   useEffect(() => {
      const webSocket = new WebSocket("ws://127.0.0.1:3000");
      setWs(webSocket);

      webSocket.addEventListener("open", () => {
         console.log("WebSocket 连接已打开");
         setIsConnected(true);
      });

      webSocket.addEventListener("error", (error) => {
         console.error("WebSocket 错误:", error);
      });

      webSocket.addEventListener("close", () => {
         console.log("WebSocket 连接已关闭");
         setIsConnected(false);
      });

      webSocket.onmessage = (event) => {
         try {
            const message = event.data;
            if (typeof message !== "string") {
               console.error("消息不是字符串:", message);
               return;
            }
            const parsedMessage = JSON.parse(message);
            const { type, content } = parsedMessage;

            switch (type) {
               case "Notices":
                  console.log("公告消息:", content);
                  getNotices();
                  break;
               case "heartbeat":
                  console.log("心跳消息:", content);
                  break;
               case "reminding":
                  console.log("消息更新:", content);
                  break;
               default:
                  console.warn("无效的消息类型:", type);
                  break;
            }
         } catch (error) {
            console.error("解析消息时出错:", error);
         }
      };

      return () => {
         webSocket.close();
      };
   }, []);

   return (
      <>
         <div>
            <div>
               标题：
               <input
                  type="text"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
               />
            </div>
            <div>
               内容：
               <textarea
                  value={content}
                  onChange={(e) => setContent(e.target.value)}
               />
            </div>
            <button onClick={sendNotices} disabled={!isConnected}>发送公告</button>
         </div>
      </>
   );
}

export default Notice;